import 'dart:math';

import 'package:chat_ai/src/models/llm_response.dart';
import 'package:chat_ai/src/services/get_llm_response.dart';
import 'package:flutter/material.dart';

import 'package:chat_ai/src/models/session_model.dart';
import 'package:flutter_chat_types/flutter_chat_types.dart' as types;
import 'package:flutter_chat_ui/flutter_chat_ui.dart';

class ChatView extends StatefulWidget {
  const ChatView({super.key, required this.sessionModel});

  final SessionModel sessionModel;

  @override
  State<StatefulWidget> createState() => _ChatViewState();
}

class _ChatViewState extends State<ChatView> {
  final List<types.Message> _messages = [];
  final List history = [];
  final _user = const types.User(id: 'user');
  var random = Random();

  void _addMessage(types.Message message) {
    setState(() {
      _messages.insert(0, message);
    });
  }

  void _handleSendPressed(types.PartialText message) async {
    final textMessage = types.TextMessage(
      author: _user,
      createdAt: DateTime.now().millisecondsSinceEpoch,
      id: random.nextDouble().toString(),
      text: message.text,
    );
    history.add({'role': 'user', 'content': message.text});
    _addMessage(textMessage);

    LlmResponse llmResponse;
    try {
      llmResponse = await getLlmResponse(widget.sessionModel, history);
    } catch (e) {
      llmResponse = LlmResponse(message: "请求失败$e");
    }
    final textResponse = types.TextMessage(
      author: const types.User(id: "assistant"),
      createdAt: DateTime.now().millisecondsSinceEpoch,
      id: random.nextDouble().toString(),
      text: llmResponse.message,
    );
    history.add({'role': 'assistant', 'content': llmResponse.message});
    _addMessage(textResponse);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.sessionModel.name),
        actions: [
          IconButton(
            icon: const Icon(Icons.more_horiz),
            onPressed: () {},
          ),
        ],
      ),
      body: Chat(
        messages: _messages,
        onSendPressed: _handleSendPressed,
        user: _user,
      ),
    );
  }
}
